// Time:  O(1), amortized
// Space: O(h)

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

# include "head/TreeNode.h"
# include <vector>
# include <iostream>
# include <cassert>
class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        pushLeft(root);
    }
    
    bool hasNext() {
        return !stk_.empty();
    }
    
    int next() {
        TreeNode *node = stk_.back();
        stk_.pop_back();
        pushLeft(node->right);
        return node->val;
    }

private:
    void pushLeft(TreeNode *node) {
        for (; node != nullptr; node = node->left) {
            stk_.emplace_back(node);
        }
    }
    std::vector<TreeNode* > stk_;
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

TreeNode* createBST(const std::vector<int>& values) {
    if (values.empty()) return nullptr;
    TreeNode* root = new TreeNode(values[0]);
    for (size_t i = 1; i < values.size(); ++i) {
        TreeNode* node = root;
        while (true) {
            if (values[i] < node->val) {
                if (node->left == nullptr) {
                    node->left = new TreeNode(values[i]);
                    break;
                } else {
                    node = node->left;
                }
            } else {
                if (node->right == nullptr) {
                    node->right = new TreeNode(values[i]);
                    break;
                } else {
                    node = node->right;
                }
            }
        }
    }
    return root;
}
 
 int main() {
    // Create a binary search tree
    std::vector<int> values = {7, 3, 15, 9, 20};
    TreeNode* root = createBST(values);

    // Create the BSTIterator
    BSTIterator iterator(root);

    // Expected in-order traversal: 3, 7, 9, 15, 20
    std::vector<int> expected = {3, 7, 9, 15, 20};
    std::vector<int> result;

    while (iterator.hasNext()) {
        result.push_back(iterator.next());
    }

    // Verify the result
    assert(result == expected);

    std::cout << "Test passed!" << std::endl;

    return 0;
 }
